package DB;
import java.sql.Connection;
import java.sql.DriverManager;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import org.logicalcobwebs.proxool.ProxoolException;
import org.logicalcobwebs.proxool.ProxoolFacade;
import org.logicalcobwebs.proxool.admin.SnapshotIF;
/**
 * 
 * proxool 连接池
 * 
 * @author Administrator
 *
 */
public class ConnManager
{
	
    static{
    	System.out.println("静态代码块begin"+new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(Calendar.getInstance().getTime()));
        try {  
            Class.forName("org.logicalcobwebs.proxool.ProxoolDriver");  //加载驱动   
        }catch (ClassNotFoundException e) {  
            System.out.println("加载驱动失败！");  
            e.printStackTrace();  
        }  
        System.out.println("静态代码块end"+new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(Calendar.getInstance().getTime()));
    } 
	
	private static int activeCount = 0;
    public ConnManager()
    {
    	
    }
    /**
     * 打开连接并返回
     * @return
     */
    public static Connection getConnection()
    {
        Connection connection = null;
        System.out.println("获取连接begin"+new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(Calendar.getInstance().getTime()));
        try
        {
        	//静态代码块中 加载 驱动
//          Class.forName("org.logicalcobwebs.proxool.ProxoolDriver");
            connection = DriverManager.getConnection("proxool.converse");
            //new ConnManager().showSnapshotInfo();
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
            System.out.println(ex.getMessage());
        }
        System.out.println("获取连接end"+new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(Calendar.getInstance().getTime()));
        return connection;
    }
    /**
     * 关闭连接
     * @param connection
     */
    public static void releaseConnection(Connection connection)
    {
        try
        {
            if(connection != null)
            {
                connection.close();
                connection = null;
            }
        }
        catch(Exception ex)
        {
            System.out.println(ex);
        }
    }
    
    /**
	 * 此方法可以得到连接池的信息 showSnapshotInfo
	 */
	private void showSnapshotInfo() {
		try {
			SnapshotIF snapshot = ProxoolFacade.getSnapshot("converse", true);
			int curActiveCount = snapshot.getActiveConnectionCount();// 获得活动连接数
			int availableCount = snapshot.getAvailableConnectionCount();// 获得可得到的连接数
			int maxCount = snapshot.getMaximumConnectionCount();// 获得总连接数
			if (curActiveCount != activeCount)// 当活动连接数变化时输出的信息
			{
				System.out.println("活动连接数:" + curActiveCount
						+ "(active)  可得到的连接数:" + availableCount
						+ "(available)  总连接数:" + maxCount + "(max)");
				activeCount = curActiveCount;
			}
		} catch (ProxoolException e) {
			e.printStackTrace();
		}
	}
	
}